package com.greenbook.security;

import com.greenbook.properties.JwtProperties;
import com.greenbook.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器
 * 用于拦截请求，验证JWT令牌并设置Spring Security上下文
 */
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final UserDetailsService userDetailsService;  // 用户详情服务
    private final JwtProperties jwtProperties;           // JWT配置属性

    /**
     * 过滤器内部处理逻辑
     *
     * @param request  HTTP请求
     * @param response HTTP响应
     * @param chain    过滤器链
     * @throws ServletException Servlet异常
     * @throws IOException      IO异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) 
            throws ServletException, IOException {
        try {
            // 从请求头中获取Authorization信息
            final String authHeader = request.getHeader("Authorization");
    
            // 如果没有token或格式不正确，直接放行
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                chain.doFilter(request, response);
                return;
            }
    
            // 提取JWT令牌（去除"Bearer "前缀）
            String jwt = authHeader.substring(7);
            
            // 如果Spring Security上下文中已有认证信息，不需要重复认证
            if (SecurityContextHolder.getContext().getAuthentication() != null) {
                chain.doFilter(request, response);
                return;
            }
    
            // 从JWT令牌中解析claims
            Claims claims = JwtUtil.parseToken(jwtProperties, jwt);
            Long userId = claims.get("userId", Long.class);
    
            if (userId != null) {
                // 加载用户详情
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(userId.toString());

                // 创建认证令牌(三个参数的构造函数会自动设置为已认证)
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userId, null, userDetails.getAuthorities());

                // 设置认证详情
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                
                // 将认证信息设置到Spring Security上下文中
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            // token解析失败，记录日志但不阻止请求
            logger.warn("JWT token解析失败: {}", e);
        } finally {
            // 无论token是否有效，都继续过滤器链
            chain.doFilter(request, response);
            // 清理Spring Security上下文，防止内存泄漏
            SecurityContextHolder.clearContext();
        }
    }
}
